# coding: utf8
import json

from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.template.context_processors import csrf

import it.views.layout as layout
from common.utils import time as th
from common.utils.http import PostVerify
from common.utils import paginator as pg
from it import config

from it.extmodels.models import ExtTasks as Tasks
from django.core.urlresolvers import reverse

from django.contrib import auth

from django.db.models import Q

from datetime import datetime



# Create your views here.
def add(req):
	'''添加工单'''
	return render(req, 'it/task_add.html', {}.update(csrf(req)))

def add_do(req):
	'''ajax,执行工单添加'''
	if req.method == 'POST':
		# 判断post token是否过期
		post_token = req.POST.get('post_token')
		pv = PostVerify(req, post_token)
		if pv.post_repeat():
			return layout.error(req=req, errors='数据已过期,请勿重复提交!')

		# 验证码校验
		captcha_session_key = req.POST.get('captcha_session_key')
		if req.session.get(captcha_session_key) != req.POST.get('verify_code'):
			return layout.error(req=req, errors='验证失败')

		# 拼接参数
		params = []
		for k,v in req.POST.items():
			if k not in ('csrfmiddlewaretoken','post_token',
						 'verify_code', 'captcha_session_key',
						 'expect_time', 'unit_time'):
				params.append('%s="%s"' % (str(k),str(v)))
		# 单独处理期望时间
		num_time = req.POST.get('expect_time')
		unit_time = req.POST.get('unit_time')
		expect_time = th.increase_time_in_now(num_time, unit_time)
		expect_time_comment = ''.join([num_time, config.get_time_unit().get(unit_time)])

		other_params = ['status=0','add_time="%s"' % th.mysql_time(),
						'level=0','irrational_level=0',
						'expect_time="%s"' % expect_time,
						'expect_time_comment="%s"' % expect_time_comment]

		try:
			# 执行命令
			eval('Tasks(%s).save()' % (',').join(params+other_params))
			pv.post_del()	# 执行成功清理post会话
		except Exception as e:
			return layout.error(req=req, errors='必填内容缺失,'+str(e.message))

		# 执行成功提示消息
		links = {
			reverse('task_list'): '查看工单列表',
			reverse('task_add'): '继续添加工单',
		}
		return layout.message(req=req, links=links)
	return layout.error(req=req)

def query_problems(req):
	'''ajax,关键词查询已有问题'''
	if req.is_ajax():
		keyword = req.POST.get('keyword')
		problems = Tasks.objects
		if keyword != '':
			# 不区分大小写包含
			problems = problems.filter(problem__icontains=keyword)
		problems = problems.values('problem').distinct()
		# 返回数据类型list [{'problem': '问题'},{'problem': '问题'}]
		return JsonResponse({'problems': [problem for problem in problems]})
	return layout.error(req)

def query_names(request):
	'''ajax,姓名查询'''
	if request.is_ajax():
		name = request.POST.get('name')

		names = Tasks.objects
		if name != '':
			names = names.filter(initiator__icontains=name)
		names = names.values('initiator').distinct()
		return JsonResponse({'names': [name for name in names]})
	return layout.error(request)

def query_addresses(request):
	'''ajax,姓名查询经常填写的地址'''
	if request.is_ajax():
		name = request.POST.get('name')

		addresses = Tasks.objects
		if name != '':
			addresses = addresses.filter(initiator__icontains=name)
		addresses = addresses.values('address').distinct()
		return JsonResponse({'addresses': [address for address in addresses]})
	return layout.error(request)

def query_phone_numbers(request):
	'''ajax,姓名查询经常填写的号码'''
	if request.is_ajax():
		name = request.POST.get('name')

		phone_numbers = Tasks.objects
		if name != '':
			phone_numbers = phone_numbers.filter(initiator__icontains=name)
		phone_numbers = phone_numbers.values('phone_number').distinct()
		return JsonResponse({'phone_numbers':
								 [phone_number for phone_number in phone_numbers]})

	return layout.error(request)


def list(req):
	'''工单列表'''
	data = {}

	# 筛选
	query = req.GET
	keyword = query.get('keyword', '')
	status = query.get('status')
	tasks = Tasks.objects.all() \
		.filter(Q(problem__icontains=keyword) \
				|Q(initiator__icontains=keyword)\
				|Q(phone_number__icontains=keyword))
	if status:
		tasks = tasks.filter(status=status)
	else:
		# 默认不包含'已取消'状态
		tasks = tasks.filter(status__gt=-1)
	page = query.get('page')
	data['tasks'] = pg.paging(tasks.order_by('-add_time', 'status'),
							  config.get_page_num(), page)
	data['status'] = config.get_status().items()
	data['query'] = query.dict()
	return render(req, 'it/task_list.html', data)

def urgent(req):
	'''加急'''
	return ''

def msg(req):
	'''留言'''
	return ''

def cancel(req):
	'''ajax,取消'''
	if req.is_ajax():

		# 验证码校验
		captcha_session_key = req.POST.get('captcha_session_key')
		if req.session.get(captcha_session_key) != req.POST.get('verify_code'):
			return JsonResponse({'code': 0, 'msg': '验证失败'})

		try:
			id = req.POST.get('id')
			task = Tasks.objects.get(id=id)
			task.status = -1
			task.cancel_time = th.mysql_time()
			task.save()
		except Exception as e:
			return JsonResponse({'code':0, 'msg':'取消失败,'+e.message})
		return JsonResponse({'code':1, 'msg':'取消成功,页面将自动刷新.'})
	return layout.error(req)

def accept(req):
	'''ajax,受理'''
	if req.is_ajax():
		try:
			user = auth.get_user(req)
			acceptor = user.last_name+user.first_name
			ids = req.POST.get('ids')
			Tasks.objects.filter(id__in=json.loads(ids))\
				.update(status=1, accept_time=th.mysql_time(), acceptor=acceptor)
		except Exception as e:
			return JsonResponse({'code':0, 'msg':'受理失败,'+e.message})
		return JsonResponse({'code': 1, 'msg': '成功标记为"已受理",页面将自动刷新.'})
	return layout.error(req)

def resolved(req):
	'''ajax,已解决'''
	if req.is_ajax():
		try:
			ids = req.POST.get('ids')
			Tasks.objects.filter(id__in=json.loads(ids))\
				.update(status=2, resolved_time=th.mysql_time())
		except Exception as e:
			return JsonResponse({'code':0, 'msg':'操作失败,'+e.message})
		return JsonResponse({'code': 1, 'msg': '成功标记为"已解决",页面将自动刷新.'})
	return layout.error(req)

def label(req):
	'''标注'''
	return ''

def unreasonable(req):
	'''不合理的加急'''
	return ''


def view(req, **kwargs):
	'''查看'''
	task = Tasks.objects.get(id=kwargs.get('task_id', None))

	return layout.display(req, 'it/task_view.html', {'task': task})

def login(req):
	'''登录'''
	# 来源url
	referer = req.META.get('HTTP_REFERER', "/")
	if 'login' in referer:
		# 若从登录页面提交, 则调整到首页
		referer = '/'
	if req.method == 'POST':
		username = req.POST.get('username')
		password = req.POST.get('password')
		next = req.POST.get('next', '/')
		user = auth.authenticate(username=username, password=password)
		if user is not None:
			auth.login(req, user)
			return redirect(next)
	return layout.display(req, 'it/login.html', {'next': referer})

def logout(req):
	'''注销'''
	auth.logout(req)
	# 跳转到next链接, 没有则返回到主页
	return redirect(req.META.get('HTTP_REFERER', "/"))


def scheduling(req):
	'''
		当天的排单
		仅包含新的和已受理的, 最新的在上面
	'''
	if req.is_ajax():
		now = datetime.today()
		start_date = datetime.strftime(now, "%Y-%m-%d 00:00:00")
		end_date = datetime.strftime(now, "%Y-%m-%d 23:59:59")

		tasks = Tasks.objects.filter(expect_time__range=(start_date, end_date))\
			.filter(Q(status=0)|Q(status=1))\
			.order_by('-expect_time').values()
		print tasks.query
		return JsonResponse({'tasks': [task for task in tasks]})

def report(req, *args, **kwargs):
	'''报表'''
	return layout.display(req, 'it/task_report.html', {})